package com.emm.yixun.mobile.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.login.LoginActivity;
import com.emm.yixun.mobile.model.EditPwd;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 修改密码
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:05:00
 */
public class UpdatePasswordActivity extends SwipeBackActivity {

    private static final String TAG = "UpdatePasswordActivity";

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 返回按钮
     */
    ImageView back_btn;

    /**
     * 当前密码
     */
    EditText search_edittext1;

    /**
     * 新密码
     */
    EditText search_edittext2;

    /**
     * 确认新密码
     */
    EditText search_edittext3;

    /**
     * 确认按钮
     */
    TextView shuerbtn;

    EditPwd epd;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onResume() {
        BaseActivity.activity = this; // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_password_activity);

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;

        initView();
        initBtn();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午5:22:56
     */
    private void initView() {
        title_main = (TextView) findViewById(R.id.title_main);
        title_main.setText(getString(R.string.personal_update_password));
        back_btn = (ImageView) findViewById(R.id.back_btn);
        back_btn.setVisibility(View.VISIBLE);
        shuerbtn = (TextView) findViewById(R.id.shuerbtn);
        search_edittext1 = (EditText) findViewById(R.id.search_edittext1);
        search_edittext2 = (EditText) findViewById(R.id.search_edittext2);
        search_edittext3 = (EditText) findViewById(R.id.search_edittext3);
        SetRelativiLayoutPadding(R.id.main_head_top_rela);
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午5:23:04
     */
    private void initBtn() {
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        shuerbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(search_edittext1.getText().toString().trim())
                        || null == search_edittext1.getText().toString().trim()) {
                    EmmApplication.T("请输入当前密码");
                } else if (search_edittext1.getText().toString().trim().length() < 6
                        || search_edittext1.getText().toString().trim().length() > 20) {
                    EmmApplication.T("密码长度在6~20位之间");
                } else if (TextUtils.isEmpty(search_edittext2.getText().toString().trim())
                        || null == search_edittext2.getText().toString().trim()) {
                    EmmApplication.T("请输入新密码");
                } else if (search_edittext2.getText().toString().trim().length() < 6
                        || search_edittext2.getText().toString().trim().length() > 20) {
                    EmmApplication.T("密码长度在6~20位之间");
                } else if (TextUtils.isEmpty(search_edittext3.getText().toString().trim())
                        || null == search_edittext3.getText().toString().trim()) {
                    EmmApplication.T("请输入确认新密码");
                } else if (search_edittext3.getText().toString().trim().length() < 6
                        || search_edittext3.getText().toString().trim().length() > 20) {
                    EmmApplication.T("密码长度在6~20位之间");
                } else if (!search_edittext2.getText().toString().trim()
                        .equals(search_edittext3.getText().toString().trim())) {
                    EmmApplication.T("新密码不一致");
                } else {
                    // EmmApplication.T("保存成功");
                    editPwd(search_edittext1.getText().toString().trim(), search_edittext3.getText().toString().trim());
                }
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 修改密码接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param loginPwd
     * @param newPwd
     * @author tangxin
     * @date 2016年12月7日 下午5:23:45
     */
    private void editPwd(String loginPwd, String newPwd) {
        EmmApplication.updateUrl("editPwd");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("loginPwd", loginPwd);// 原密码
        map.put("newPwd", newPwd);// 新密码
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("editPwd-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(UpdatePasswordActivity.this, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                epd = JSONObject.parseObject(resData.toString(), EditPwd.class);

                if ("1".equals(epd.getResult())) {
                    Log.v("获取成功", "");

                    EmmApplication.T("修改成功");

                    // 重置登陆信息
                    EmmApplication.setIsLogin("2");
                    EmmApplication.setIsLoginToken("");
                    EmmApplication.setIsLoginUserId("");

                    Intent intent = new Intent();
                    intent.putExtra("GO", "2");
                    intent.setClass(UpdatePasswordActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                    sendBroadcast(new Intent(EmmApplication.logout));// 广播通知

                } else {
                    EmmApplication.T(epd.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + epd.getErrorCode().toString() + "errorMsg:"
                            + epd.getErrorMsg().toString());
                }
            }
        });
    }
}
